/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import entidade.persistencia.TipoUsuario;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.Permissao;
import entidade.persistencia.Usuario;
import java.util.List;
import java.util.List;
import ws.converter.TipoUsuarioConverter;

/**
 *
 * @author victorinox
 */

public class TipoUsuarioResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of TipoUsuarioResource */
    public TipoUsuarioResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of TipoUsuario identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of TipoUsuarioConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public TipoUsuarioConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new TipoUsuarioConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of TipoUsuario identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an TipoUsuarioConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(TipoUsuarioConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of TipoUsuario identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of TipoUsuario identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of TipoUsuario
     */
    protected TipoUsuario getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (TipoUsuario) em.createQuery("SELECT e FROM TipoUsuario e where e.tipoUsuarioId = :tipoUsuarioId").setParameter("tipoUsuarioId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected TipoUsuario updateEntity(TipoUsuario entity, TipoUsuario newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<Permissao> permissaoCollection = entity.getPermissaoCollection();
        List<Permissao> permissaoCollectionNew = newEntity.getPermissaoCollection();
        List<Usuario> usuarioCollection = entity.getUsuarioCollection();
        List<Usuario> usuarioCollectionNew = newEntity.getUsuarioCollection();
        entity = em.merge(newEntity);
        for (Permissao value : permissaoCollection) {
            if (!permissaoCollectionNew.contains(value)) {
                value.getTipoUsuarioCollection().remove(entity);
            }
        }
        for (Permissao value : permissaoCollectionNew) {
            if (!permissaoCollection.contains(value)) {
                value.getTipoUsuarioCollection().add(entity);
            }
        }
        for (Usuario value : usuarioCollection) {
            if (!usuarioCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from usuarioCollection"));
            }
        }
        for (Usuario value : usuarioCollectionNew) {
            if (!usuarioCollection.contains(value)) {
                TipoUsuario oldEntity = value.getTipoUsuarioId();
                value.setTipoUsuarioId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getUsuarioCollection().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(TipoUsuario entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        for (Permissao value : entity.getPermissaoCollection()) {
            value.getTipoUsuarioCollection().remove(entity);
        }
        if (!entity.getUsuarioCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because usuarioCollection is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of PermissaoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of PermissaoesResource
     */
    @Path("permissaoCollection/")
    public PermissaoesResource getPermissaoCollectionResource() {
        PermissaoCollectionResourceSub resource = resourceContext.getResource(PermissaoCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of UsuarioesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioesResource
     */
    @Path("usuarioCollection/")
    public UsuarioesResource getUsuarioCollectionResource() {
        UsuarioCollectionResourceSub resource = resourceContext.getResource(UsuarioCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class PermissaoCollectionResourceSub extends PermissaoesResource {

        private TipoUsuario parent;

        public void setParent(TipoUsuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Permissao> getEntities(int start, int max, String query) {
            List<Permissao> result = new java.util.ArrayList<Permissao>();
            int index = 0;
            for (Permissao e : parent.getPermissaoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class UsuarioCollectionResourceSub extends UsuarioesResource {

        private TipoUsuario parent;

        public void setParent(TipoUsuario parent) {
            this.parent = parent;
        }

        @Override
        protected List<Usuario> getEntities(int start, int max, String query) {
            List<Usuario> result = new java.util.ArrayList<Usuario>();
            int index = 0;
            for (Usuario e : parent.getUsuarioCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
